<template>
  <div class="upload-cover" @click="dialogCoverVisible = true">
    <div class="cover-warp">
      <img class="cover-image" ref="cover-image" :src="value" />
    </div>
    <el-dialog
      title="选择封面"
      :visible.sync="dialogCoverVisible"
      append-to-body
    >
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="first">
          <!--
            ref 有两个作用：
            （1）作用到普通 html 标签上可以获取dom；
            （2）作用到组件上可以获取组件
          -->
          <ImageList
            :is-show-add="false"
            :is-show-action="false"
            is-show-selected
            ref="images-list"
          />
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="second">
          <input type="file" ref="file" @change="onFileChange" />
          <img width="100" ref="preview-image" />
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogCoverVisible = false">取 消</el-button>
        <el-button type="primary" @click="onCoverFirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadImage } from '@/api/image'
import ImageList from '../../images/components/image-list.vue'
export default {
  name: 'UploadCover',
  components: { ImageList },
  props: ['value'],
  data () {
    return {
      dialogCoverVisible: false,
      activeName: 'first' // 默认展示的选项卡
    }
  },
  computed: {},
  watch: {},
  mounted () { },
  methods: {
    onFileChange () {
      // 获取文件对象
      const file = this.$refs.file.files[0]
      //   图片预览
      const blob = window.URL.createObjectURL(file)
      this.$refs['preview-image'].src = blob
      //   this.$refs.file.value = ''
    },
    async onCoverFirm () {
      // 如果tab 是上传图片，且input-file 有选择文件，才执行上传图片操作
      if (this.activeName === 'second') {
        const file = this.$refs.file.files[0]
        if (!file) {
          this.$message('请选择文件')
          return false
        }
        // 执行上传文件操作
        const fd = new FormData()
        fd.append('image', file)
        const { data } = await uploadImage(fd)
        // console.log(data)
        this.dialogCoverVisible = false
        this.$refs['cover-image'].src = data.data.url
        // this.$emit('upload-cover', data.data.url)
        this.$emit('input', data.data.url)
      } else if (this.activeName === 'first') {
        // 另一种组件通信方式：父组件可以通过 ref 直接访问子组件中的数据
        const imageList = this.$refs['images-list']
        const selected = imageList.selected
        if (selected == null) {
          this.$message.error('请选择封面图片')
          return false
        }
        // 关闭对话框
        this.dialogCoverVisible = false
        // 修改父组件绑定数据
        this.$emit('input', imageList.images[selected].url)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cover-warp {
  width: 150px;
  height: 120px;
  border: 1px solid #000;
  .cover-image {
    height: 120px;
    max-width: 100%;
  }
}
</style>
